<template>
	<view>
		<view class="padding-box">
			<view class="body-item">
				<text>讨论组名称</text>
				<input class="passText" type="text" value="" maxlength="20" placeholder="请输入" v-model="group_name" />
			</view>
			
			<view class="body-item">
				<text>讨论组封面</text>
				<view class="uploadImg" @tap="getToken('headImg')">
					<image v-if="userHeadImg==''" src="../../../static/index/zhaopian.png" mode=""></image>
					<image v-else :src="userHeadImg" mode=""></image>
				</view>
			</view>
			
			<view class="body-item">
				<text>语言</text>
				<view class="body-right" @tap="toLanuage">
					<text v-if="language==''">请选择</text>
					<text v-else>{{language}}</text>
					<image src="../../../static/right.png" mode=""></image>
				</view>
			</view>
			
			<view class="body-item">
				<view class="uni-title uni-common-pl">面向人群</view>			
				<view class="uni-list-cell-db body-right">
					<picker @change="bindPickerChange" :value="index" :range="Forthecrowd">
						<text class="uni-input">{{Forthecrowd[index]}}</text>
						<image src="../../../static/right.png" mode=""></image>
					</picker>
				</view>
			</view>
			
			<view class="body-item" @tap="toLabel">
				<text>标签</text>
				<view class="body-right">
					<text v-if="Theme_item==''&&Theme_name==''">请选择</text>
					<text v-else>{{Theme_name}}/{{Theme_item}}</text>
					<image src="../../../static/right.png" mode=""></image>
				</view>
			</view>
						
			<view class="body-item">
				<view class="uni-title uni-common-pl">最大连麦人数</view>
				<view class="uni-list-cell-db body-right">
					<picker @change="bindNmuChange" :value="maximum" :range="maximum">
						<text class="uni-input">{{maximum[indexs]}}</text>
						<image src="../../../static/right.png" mode=""></image>
					</picker>
				</view>
			</view>
		</view>
		
		<view class="margin-box body-item2">
			<view class="">
				类别
			</view>
			<view class="type-box">
				<view class="type-item" v-for="(item,index) in typeList" :key="index" :class="{active:index==typeIndex}" @tap="chooseIndex(index)">
					{{item}}
				</view>
			</view>
		</view>
		<view class="shuoming">说明：创建普通语音房间不需要消耗猫币，创建在线语音或在线视频房间则需要消耗100猫币，在该房间所获得收益，平台将收取30%的管理费</view>
		<view class="btn" @tap="creatGroup">
			确认
		</view>
	</view>
</template>

<script>
	import wh from '../../../wxcomponents/mlvb-live-room/webim_handler.js'
	import qiniu from '../../../common/qiniuUploader.js'
	export default {
		data() {
			return {
				Forthecrowd: ['儿童', '少年', '大学生', '成人'],
				maximum:['1','2','3','4','5','6'],
				index:'',
				indexs:'',
				ageGrade:'',
				typeList: ['语音直播课堂', '视频直播课堂'],
				typeIndex: 0,
				number: 100, //猫币数
				showNumList: false,
				peopleNum: 0, //人数
				language: '', //语言
				peopleType: '', // 人群对象
				group_name: '', //群名称
				Theme_name: '',
				Theme_item: '',
				userHeadImg: '',
				enName:'',
			}
		},
		onShow() {
			if (uni.getStorageSync('motherLanguage')) {
				var thelangeauge = uni.getStorageSync('motherLanguage')
				thelangeauge.map( item=>{
					console.log(item.enName)
					this.language = item.name
					this.enName = item.enName
				})
				
			}
			if (uni.getStorageSync('Theme_name') != undefined || uni.getStorageSync('Theme_name') != '') {
				this.Theme_name = uni.getStorageSync('Theme_name')
			}
			if (uni.getStorageSync('Theme_item') != undefined || uni.getStorageSync('Theme_item') != '') {
				this.Theme_item = uni.getStorageSync('Theme_item')
			}
			if(uni.getStorageSync('peopleType')){
				this.peopleType = uni.getStorageSync('peopleType')
			}
		},
		onUnload() {
			uni.removeStorageSync('motherLanguage')
			uni.removeStorageSync('Theme_name')
			uni.removeStorageSync('Theme_item')
			uni.removeStorageSync('peopleType')
		},
		methods: {
			bindPickerChange: function(e) {
			    console.log('picker发送选择改变，携带值为', e.target.value)
			    this.index = e.target.value
			},
			bindNmuChange:function(e){
				this.indexs = e.target.value
			},
			getToken() {
				var me = this;
				var data = {
					key: null,
					type:'223',
				}
				this.myAjaxNewPost({
					model: 'push',
					controllerName: 'upload',
					actionName: 'getToken',
					data: data,
					successBack: function(res) {			
						me.token = res.data.data
						console.log(me.token)
						if (me.token != '') {
							me.selectImg()
						}
			
					}
				})
			},
			selectImg() { //上传头像
				var me = this;
				uni.showActionSheet({
					itemList: ['拍照', '相册'],
					itemColor: '#008AFF',
					success: function(res) {
						var index = res.tapIndex;
						if (index == 1) {
							uni.chooseImage({
								count: 1, //默认9
								sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
								sourceType: ['album'], //从相册选择
								success: function(res) {
									console.log(res)
									var filePath = res.tempFilePaths[0];
									// console.log(JSON.stringify(res.tempFilePaths));
									// 交给七牛上传
									if (me.token != '') {
										uni.showLoading({
											title: '上传中'
										})
										qiniu.upload(filePath, (res) => {
											console.log(res.imageURL)
											var imageURL = res.imageURL
											me.userHeadImg = imageURL
											uni.hideLoading()
											console.log('file url is: ' + res.fileUrl);
										}, (error) => {
											uni.showToast({
												title: '上传失败',
												icon: null
											});
											console.log('error: ' + error);
										}, {
											region: 'ECN',
											domain: 'http://img.curiousmore.com', // // bucket 域名，下载资源时用到。如果设置，会在 success callback 的 res 参数加上可以直接使用的 ImageURL 字段。否则需要自己拼接
											key: uni.getStorageSync('user_id')+'groupHead'+me.generateMixed(8) , // [非必须]自定义文件 key。如果不设置，默认为使用微信小程序 API 的临时文件名
											// 以下方法三选一即可，优先级为：uptoken > uptokenURL > uptokenFunc
											uptoken: me.token, // 由其他程序生成七牛 uptoken
											// uptokenURL: 'http://192.168.6.6:8768/eg-api/push/upload/getToken', // 从指定 url 通过 HTTP GET 获取 uptoken，返回的格式必须是 json 且包含 uptoken 字段，例如： {"uptoken": "[yourTokenString]"}
											uptokenFunc: function() {
												return '[yourTokenString]';
											}
										}, (res) => {
											console.log('上传进度', res.progress)
											console.log('已经上传的数据长度', res.totalBytesSent)
											console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
			
										}, () => {
											// 取消上传
										}, () => {
											// `before` 上传前执行的操作
										}, (err) => {
											// `complete` 上传接受后执行的操作(无论成功还是失败都执行)
			
										});
									}
			
								}
							});
						} else if (index == 0) {
							uni.chooseImage({
								count: 1, //默认9
								sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
								sourceType: ['camera '], //相机
								success: function(res) {
									// console.log(JSON.stringify(res.tempFilePaths));
									var filePath = res.tempFilePaths[0];
									// console.log(JSON.stringify(res.tempFilePaths));
									// 交给七牛上传
									if (me.token != '') {
										uni.showLoading({
											title: '上传中'
										})
										qiniu.upload(filePath, (res) => {
											console.log(res.imageURL)
											var imageURL = res.imageURL
											me.userHeadImg = imageURL
											uni.hideLoading()
											console.log('file url is: ' + res.fileUrl);
										}, (error) => {
											uni.showToast({
												title: '上传失败',
												icon: null
											});
											console.log('error: ' + error);
										}, {
											region: 'ECN',
											domain: 'http://img.curiousmore.com', // // bucket 域名，下载资源时用到。如果设置，会在 success callback 的 res 参数加上可以直接使用的 ImageURL 字段。否则需要自己拼接
											key: uni.getStorageSync('user_id')+'groupHead'+me.generateMixed(8), // [非必须]自定义文件 key。如果不设置，默认为使用微信小程序 API 的临时文件名
											// 以下方法三选一即可，优先级为：uptoken > uptokenURL > uptokenFunc
											uptoken: me.token, // 由其他程序生成七牛 uptoken
											// uptokenURL: 'http://192.168.6.6:8768/eg-api/push/upload/getToken', // 从指定 url 通过 HTTP GET 获取 uptoken，返回的格式必须是 json 且包含 uptoken 字段，例如： {"uptoken": "[yourTokenString]"}
											uptokenFunc: function() {
												return '[yourTokenString]';
											}
										}, (res) => {
											console.log('上传进度', res.progress)
											console.log('已经上传的数据长度', res.totalBytesSent)
											console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
										}, () => {
											// 取消上传
										}, () => {
											// `before` 上传前执行的操作
										}, (err) => {
											// `complete` 上传接受后执行的操作(无论成功还是失败都执行)
			
										});
									}
								}
							});
						}
					}
				});
			},
			generateMixed(n) {
				var chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
					'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
					'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
				];
				var res = "";
				for (var i = 0; i < n; i++) {
					var id = Math.ceil(Math.random() * 17);
					res += chars[id];
				}
				return res;
			},
			chooseIndex(index) {
				this.typeIndex = index
			},
			seletInput() {
				var containSpecial = RegExp(
					/[(\ )(\~)(\!)(\@)(\#)(\$)(\%)(\^)(\&)(\*)(\()(\))(\-)(\_)(\+)(\=)(\[)(\])(\{)(\})(\|)(\\)(\;)(\:)(\')(\")(\,)(\.)(\/)(\<)(\>)(\?)(\)(\u4e00-\u9fa5)(A-Za-z)]+/
				);
				if (containSpecial.test(this.number) == true) {
					this.showbtn = false;
					uni.showToast({
						title: '请输入正确的金额',
						icon: 'none'
					})
					this.number = 100;
				}
			},
			toLanuage() {
				uni.navigateTo({
					url: '/pages/Other/countrySelect/countrySelect?type=语言学习&kind=mother'
				})
			},
			toLabel() {
				uni.navigateTo({
					url: '../../../pages/My/selectClassTheme/selectClassTheme'
				})
			},
			toPeopleType(){
				uni.navigateTo({
					url:'../../../pages/My/selectType/selectType'
				})
			},
			creatGroup() {
				let _self = this
				if (this.group_name == '') {
					uni.showToast({
						title: '请输入群名',
						icon: 'none'
					})
					return
				}
				if (this.userHeadImg == '') {
					uni.showToast({
						title:'请添加封面',
						icon:'none'
					})
					return
				}
				if (this.language == '') {
					uni.showToast({
						title: '请选择语言',
						icon: 'none'
					})
					return
				}
				if (this.Theme_name == '' && this.Theme_item == '') {
					uni.showToast({
						title: '请选择标签',
						icon: 'none'
					})
					return
				}
				if(this.index == ''){
					uni.showToast({
						title:'请选择面向对象',
						icon:"none"
					})
					return
				}
				if(this.indexs == ''){
					uni.showToast({
						title:'请选择最多连麦人数',
						icon:"none"
					})
					return
				}
				if (this.typeIndex == 0) {
					var type = 'online_voice'
					var pureAudio = true
				} else if (this.typeIndex == 1) {
					var type = 'online_video'
					var pureAudio = false
				}
				var ageGrade;
				if(this.index == 0){
					ageGrade = 'Childhood'
				}else if(this.index == 1){
					ageGrade = 'Teenagers'
				}else if(this.index == 2){
					ageGrade = 'University Student'
				}else if(this.index == 3){
					ageGrade = 'Adult'
				}				
				var data = {
					group_name: this.group_name,
					type: type,
					language: this.enName,
					peopleNum: this.indexs+1,
					label: this.Theme_name + '/' + this.Theme_item,
					owner_id:uni.getStorageSync('user_id'),
					group_type:'Public',
					faceUrl:this.userHeadImg,
					age_grade:ageGrade,
					owner_id : uni.getStorageSync('user_id')
				}
				this.myAjaxNewPost({
					model: 'message',
					controllerName: 'messageGroup',
					actionName: 'insert',
					data: data,
					successBack: function(res) {
						if(res.data.code){
							uni.showToast({
								title:'创建失败'
							})
						}else{						
							let userInfo = wx.getStorageSync('user_info')
							let userName = wx.getStorageInfoSync('nick_name')
							let itemRoom = {
								groupName:data.group_name,
								label:data.label,
								language:data.language,
								onlineNum:1,
								flag:userInfo.national_flag,
								groupAvatar:userInfo.avatar,
								userName: userInfo.nick_name || '暂无昵称',
								userId: wx.getStorageSync('user_id'),
								payRoomId:res.data.data.id
							}
							var url = '/pages/Meet/MLVBRoom/MLVBRoom?type=create&roomName=' + _self.group_name + '&userName=' + userName +'&pureAudio=' + pureAudio +  '&itemRoom=' + JSON.stringify(itemRoom);
							wx.setStorageSync('liveAnchorID', wx.getStorageSync('user_id'))
							wx.setStorageSync('liveRoomID', res.data.data.groupId)
							uni.setStorageSync('RoomID', res.data.data.id)
							uni.redirectTo({
								url: url
							});
							uni.showToast({
								title: '进入房间',
								icon: 'success',
								duration: 1000
							})
						}
					},
				})
			},
		}
	}
</script>

<style scoped>
	.body-item {
		background: #FFFFFF;
		padding: 0 24upx;
		border-bottom: 1upx solid #E6E6E6;
		display: flex;
		justify-content: space-between;
		align-items: center;
		height: 88upx;
		font-size: 32upx;
		/* font-weight: 400; */
	}

	.body-item image {
		width: 16upx;
		height: 28upx;
		margin-left: 30upx;
	}
	.body-item .uploadImg image{
		width: 70upx;
		height: 70upx;
		border-radius: 50%;
	}
	.body-right {
		font-size: 28upx;
		color: #999999;
		/* font-weight: 100; */
	}

	.margin-box {
		margin-top: 20upx;
	}

	.body-item2 {
		font-size: 32upx;
		color: #333333;
		/* font-weight: bold; */
		background: #FFFFFF;
		padding: 15upx 24upx;
	}

	.type-box {
		display: flex;
		flex-wrap: wrap;
	}

	.type-item {
		width: 180upx;
		height: 58upx;
		text-align: center;
		line-height: 58upx;
		color: #666666;
		font-size: 26upx;
		border-radius: 29upx;
		border: 1upx solid #E6E6E6;
		margin: 24upx 26upx;
		/* font-weight: 100; */
	}

	.active {
		color: #FFFFFF;
		background: linear-gradient(-90deg, rgba(50, 242, 226, 1), rgba(50, 226, 242, 1));
		border: 1upx solid #FFFFFF;
	}

	.number-select {
		width: 170upx;
		height: 48upx;
		background: rgba(255, 255, 255, 1);
		border: 1upx solid rgba(230, 230, 230, 1);
		border-radius: 10upx;
	}

	.passText {
		text-align: right;
	}

	/*加号*/
	.right-box {
		display: inline-block;
		background: rgba(153, 153, 153, 1);
		height: 24upx;
		position: relative;
		width: 2upx;
	}

	.right-box::after {
		background: rgba(153, 153, 153, 1);
		content: "";
		height: 24upx;
		left: 0;
		position: absolute;
		top: 0;
		width: 2upx;
		transform: rotateZ(90deg)
	}

	.center-box {
		width: 40%;
		height: 100%;
		color: rgba(51, 51, 51, 1);
		font-size: 24upx;
		border-left: 1upx solid rgba(230, 230, 230, 1);
		border-right: 1upx solid rgba(230, 230, 230, 1);
		text-align: center;
	}

	.border-box {
		width: 29.9%;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 24upx;
		color: rgba(51, 51, 51, 1);
	}

	/*减号*/
	.left-box {
		display: inline-block;
		background: rgba(153, 153, 153, 1);
		height: 24upx;
		position: relative;
		width: 2upx;
		transform: rotateZ(90deg);
		text-align: center;
		line-height: 48upx;
	}

	.shuoming {
		font-size: 22upx;
		color: #999999;
		padding: 38upx 24upx;
	}

	.people_Num-box {
		display: flex;
		justify-content: space-between;
		font-size: 32upx;
		padding: 20upx 24upx 0 24upx;
		position: relative;
	}

	.people_Num {
		background: #FFFFFF;
		border: 1upx solid #E6E6E6;
		width: 170upx;
		height: 48upx;
		border-radius: 24upx;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.people_Num text {
		margin-left: 56upx;
	}

	.people_Num image {
		width: 26upx;
		height: 15upx;
		margin-right: 20upx;
	}

	.btn {
		margin-bottom: 60upx;
	}

	.numListBox {
		position: absolute;
		display: flex;
		flex-direction: column;
		background: #FFFFFF;
		border: 1upx solid #E6E6E6;
		border-radius: 10upx;
		align-items: center;
		line-height: 60upx;
		right: 100upx;
		top: -580upx;
		z-index: 9999;
	}

	.numListItem {
		border-bottom: 1upx solid #E6E6E6;
		padding: 0upx 20upx;
		color: #333333;
		font-size: 28upx;
	}
</style>
